import asyncio
import time

async def task_fun( para ):
    print("========begin========")
    await asyncio.sleep( 2 ) 
    print("========end========") 
    return para

class AsyncSerial:

    def __init__( self, port, baud ):
        self.port = port
        self.baud = baud
        self.count = 1
        self.now_time = time.time()
        pass

    ## TODO  字节校验
    def validate(self, ):
        return True

    def exit_corroutine(self, ):
        ## 校验
        if not self.validate():
            return False
        ## 超时
        if time.time() - self.now_time > 30:
            return False
        return True

    async def open(self, ):
        await asyncio.sleep(2)

    async def connect(self ):
        await asyncio.sleep(2)

    async def fetch(self, ):
        print("========begin========")
        await asyncio.sleep( 0.2 ) 
        print("========end========") 
        return 1

    async def start(self,):
        self.now_time = time.time()
        while self.count < 100 :
            res = await self.handle( )
            self.count += res
            print(f" self.count ..... { self.count} ")
            print(f" {int(self.now_time)} ..... { int( time.time())} ")
            if time.time() - self.now_time > 30:
                print("timeout ..... ")
                break

    async def handle(self, ):
        # ser = serial.serial(port,baud, timeout = 0.5)
        loop = asyncio.get_event_loop()
        # task = asyncio.create_task(ser.read_all())
        task = asyncio.ensure_future(task_fun(self.count))
        data = await task
        print(f" data ..... { data} ")
        return data

s = AsyncSerial( "COM1", 9600 )
asyncio.run( s.start() )

import asyncio
import serial

class SerialProtocol(asyncio.Protocol):
    def __init__(self, loop, serial_port):
        self.loop = loop
        self.serial_port = serial_port

    def connection_made(self, transport):
        self.transport = transport
        print('串口连接建立')
        self.send_message()

    def data_received(self, data):
        message = data.decode('utf-8')
        print(f'接收到消息: {message}')

    def send_message(self):
        message = b'Hello, World!\n'
        self.transport.write(message)
        print(f'已发送消息: {message.decode("utf-8")}')

    def connection_lost(self, exc):
        print('串口连接丢失')

async def main():
    loop = asyncio.get_running_loop()
    serial_port = '/dev/ttyUSB0'  
    serial_protocol = SerialProtocol(loop, serial_port)
    transport, protocol = await loop.create_connection(lambda: serial_protocol, serial_port)
    try:
        await asyncio.sleep(10)  
    finally:
        transport.close()

if __name__ == "__main__":
    asyncio.run(main())